<?php
namespace app\service;

use app\model\MemberWalletLogModel;
use app\model\MemberWalletModel;
use support\Db;
use const support\business_types_1;
use const support\business_types_2;
use const support\business_types_remarks;
use const support\business_types_structs;
use const support\CORRECT;
use const support\direction_in;
use const support\direction_out;
use const support\wallet_types_1;
use support\facade\Logger;

class MemberWalletService
{

    //佣金明细
    public static function CommissionDetails(int $memberId,int $page,int $limit): array
    {
        $model=MemberWalletLogModel::where([
            'wallet_type'=>wallet_types_1,
            'member_id'  =>$memberId,
            'direction'  =>direction_in
        ]);
        //查询符合要求总数据
        $totalNum=$model->count();
        //查询数据
        $offset=($page-1)*$limit;
        $lists=$model->offset($offset)->limit($limit)->select([
            'id','member_id','change_amount','current_balance','business_types_struct','create_time'
        ])->get()->toArray();
        $lists=array_map(function($row) {
            $businessTypesStruct=$row['business_types_struct'];
            $row['order_sn']=$businessTypesStruct['order_sn']??'';
            $row['order_id']=$businessTypesStruct['order_id']??0;
            unset($row['business_types_struct']);
            return $row;
        },$lists);
        return commonPagingData($lists,$page,$limit,$totalNum);
    }

    //获取用户可提现金额
    public static function getWithdrawAbleAmount(int $memberId){
        $wallet= MemberWalletModel::where([
            'member_id'=>$memberId,
            'wallet_type'=>wallet_types_1,
            'status'=>CORRECT
        ])->first();
        if (empty($wallet->id)){
            return 0;
        }
        $wallet=$wallet->append(['available_balance'])->toArray();
        return $wallet['available_balance']??0;
    }

    //账户确认提现操作
    public static function toWithdrawalMemberWalletData(int $walletType,int $memberId,int $direction,float $changeAmount,string $sn='',int $id=0): bool
    {
        $where=[
            'wallet_type'   =>$walletType,
            'member_id'     =>$memberId,
            'status'        => CORRECT
        ];
        //获取当前用户钱包信息
        $memberWallet=MemberWalletModel::firstOrCreate($where,[
            'create_time'=>time()
        ]);
        Db::beginTransaction();
        try {
            //更新钱包主表信息
            $ret=MemberWalletModel::where($where)->decrement('frozen_amount',$changeAmount);
            Logger::app('账户资金变动流水操作：更新钱包主表信息1','info',[$ret]);
            if ($direction==direction_out){
                $ret=MemberWalletModel::where($where)->decrement('balance',$changeAmount);
                Logger::app('账户资金变动流水操作：更新钱包主表信息2','info',[$ret]);
                $currentBalance=$memberWallet->balance-$changeAmount;
                $business_types_struct=business_types_structs[business_types_2]??[];
                $business_types_struct['withdrawal_sn']=$sn;
                $business_types_struct['withdrawal_id']=$id;
                //新增钱包流水日志信息
                $insert=[
                    'wallet_type'=>$walletType,
                    'wallet_id'  =>$memberWallet->id,
                    'member_id'  =>$memberId,
                    'direction'  =>$direction,
                    'change_amount'=>$changeAmount,
                    'current_balance'=>$currentBalance,
                    'past_balance'=>$memberWallet->balance,
                    'business_type'=>business_types_2,
                    'business_type_name'=>business_types_remarks[business_types_2],
                    'business_types_struct'=>json_encode($business_types_struct),
                    'create_time'=>time()
                ];
                $ret=MemberWalletLogModel::insertGetId($insert);
                Logger::app('账户资金变动流水操作：新增钱包流水日志信息','info',[$ret,$insert]);
            }
            Db::commit();
            return true;
        }catch (\Throwable $e){
            Db::rollBack();
            Logger::app($e);
            return false;
        }
    }

    //账户资金变动流水操作
    public static function addMemberWalletData(int $walletType,int $memberId,int $businessType,int $direction,float $changeAmount,string $sn='',int $id=0): bool
    {
        $where=[
            'wallet_type'   =>$walletType,
            'member_id'     =>$memberId,
            'status'        => CORRECT
        ];
        //获取当前用户钱包信息
        $memberWallet=MemberWalletModel::firstOrCreate($where,[
            'create_time'=>time()
        ]);
        Db::beginTransaction();
        try {
            //更新钱包主表信息
            if ($direction==direction_in){
                $ret=MemberWalletModel::where($where)->increment('balance',$changeAmount);
                Logger::app('账户资金变动流水操作：更新钱包主表信息1','info',[$ret]);
                $ret=MemberWalletModel::where($where)->increment('total_amount',$changeAmount);
                Logger::app('账户资金变动流水操作：更新钱包主表信息2','info',[$ret]);
                $currentBalance=$memberWallet->balance+$changeAmount;
            }else{
                $ret=MemberWalletModel::where($where)->decrement('balance',$changeAmount);
                Logger::app('账户资金变动流水操作：更新钱包主表信息3','info',[$ret]);
                $currentBalance=$memberWallet->balance-$changeAmount;
            }
            $business_types_struct=business_types_structs[$businessType]??[];
            if ($businessType==business_types_1){
                $business_types_struct['order_sn']=$sn;
                $business_types_struct['order_id']=$id;
            }elseif ($businessType==business_types_2){
                $business_types_struct['withdrawal_sn']=$sn;
                $business_types_struct['withdrawal_id']=$id;
            }
            //新增钱包流水日志信息
            $insert=[
                'wallet_type'=>$walletType,
                'wallet_id'  =>$memberWallet->id,
                'member_id'  =>$memberId,
                'direction'  =>$direction,
                'change_amount'=>$changeAmount,
                'current_balance'=>$currentBalance,
                'past_balance'=>$memberWallet->balance,
                'business_type'=>$businessType,
                'business_type_name'=>business_types_remarks[$businessType],
                'business_types_struct'=>json_encode($business_types_struct),
                'create_time'=>time()
            ];
            $ret=MemberWalletLogModel::insertGetId($insert);
            Logger::app('账户资金变动流水操作：新增钱包流水日志信息','info',[$ret,$insert]);
            Db::commit();
            return true;
        }catch (\Throwable $e){
            Db::rollBack();
            Logger::app($e);
            return false;
        }
    }


}